﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ODS.Config;
using ODS.Utils;
using System.IO;
using ODS.Model;
using System.Windows;

namespace ODS.WebService.DeviceMonitor
{
    public class AddDeviceMonitorService
    {
        static bool IsAuthenticated = true;

        public static async Task<InfoResult> AddDeviceMonitor(DeviceMonitorModel monitor, String imei, String typeMonitor)
        {
            String url = Constants.SERVER_URL + "/devices/" + imei + "/monitors";
            String body ="";

            switch (int.Parse( typeMonitor)) {
                case 6:
                case 7:
                case 5:
                {
                        body=String.Format("<monitorInfo><monitorType>{0}</monitorType></monitorInfo>",typeMonitor);
                }
                break;
                case 4:
                    break;
                case 3:
                {
                    MonitorParameterModel parameterIndex = null;
                    MonitorParameterModel parameterLatitude = null;
                    MonitorParameterModel parameterLongitude = null;
                    MonitorParameterModel parameterRadius = null;
                    foreach(MonitorParameterModel parameterModel in monitor.ArrayParameter )
                    {
                        if(parameterModel.NameParameter.Equals("index"))
                        {
                            parameterIndex = parameterModel;
                        }
                        if(parameterModel.NameParameter.Equals("latitude"))
                        {
                            parameterLatitude = parameterModel;
                    
                        }
                        if(parameterModel.NameParameter.Equals("longitude"))
                        {
                            parameterLongitude = parameterModel;
                        }
                        if(parameterModel.NameParameter.Equals("radius"))
                        {
                            parameterRadius = parameterModel;
                        }
                
                    }

                    body = String.Format("<monitorInfo><monitorType>{0}</monitorType><parameter><name>index</name><value>{1}</value></parameter><parameter><name>latitude</name><value>{2}</value></parameter><parameter><name>longitude</name><value>{3}</value></parameter><parameter><name>radius</name><value>{4}</value></parameter></monitorInfo>",
                                                                typeMonitor,
                                                                parameterIndex.Value,
                                                                parameterLatitude.Value,
                                                                parameterLongitude.Value,
                                                                parameterRadius.Value);

                }
                    break;
                case 2:
                {
                    MonitorParameterModel parameterThreshold = null;
                    foreach(MonitorParameterModel parameterModel in monitor.ArrayParameter )
                    {
                        if(parameterModel.NameParameter.Equals("threshold"))
                        {
                            parameterThreshold = parameterModel;
                            break;
                        }
                    }
                    body = String.Format("<monitorInfo><monitorType>{0}</monitorType><parameter><name>threshold</name><value>{1}</value></parameter></monitorInfo>",
                                            typeMonitor,
                                            parameterThreshold.Value);

                }
                    break;
                case 1:
                {
                    MonitorParameterModel parameterPeriod= null;
                    foreach (MonitorParameterModel parameterModel in monitor.ArrayParameter )
                    {
                        if(parameterModel.NameParameter.Equals("period"))
                        {
                            parameterPeriod = parameterModel;
                            break;
                        }

                    }
                        body = String.Format( "<monitorInfo><monitorType>{0}</monitorType><parameter><name>period</name><value>{1}</value></parameter></monitorInfo>",
                                                typeMonitor,
                                                parameterPeriod.Value);
                }
                    break;
            
                default:
                    break;
            }

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPPostRequest(url, body);
                String resultString = ParseXML(xmlStream);

                #region check authenticate
                if (!IsAuthenticated)
                {                   
                    InfoResult result_login = await Login_Logout.LoginService.loginService(App.userLogin.UserLoginName, App.userLogin.UserPassword);
                    if (result_login.IsSuccess)
                    {
                        if ((String)result_login.ReturnedObject == Constants.SUCCESS)
                        {
                            IsAuthenticated = true;

                            return await AddDeviceMonitor(monitor, imei, typeMonitor);
                        }
                        else
                        {
                            MessageBox.Show((String)result_login.ReturnedObject);
                            App.BackToLoginPage();
                            
                        }
                    }
                    else
                    {
                        MessageBox.Show(result_login.Error);
                        App.BackToLoginPage();
                        
                    }


                }
                #endregion

                result = new InfoResult(null, resultString);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }

            return result;
        }

        

        private static String ParseXML(Stream xmlStream)
        {
            XDocument doc = XDocument.Load(xmlStream);

            var Authenticate = (from authen in doc.Descendants("unauthorized")
                        select new
                        {
                            
                        }).FirstOrDefault();
            if (Authenticate != null)
            {
                IsAuthenticated = false;
                return null;
            }

            var Nack = (from nack in doc.Descendants("nack")
                        select new
                        {
                            Message = nack.Element("message").Value,
                        }).FirstOrDefault();

            if (Nack != null)
            {
                return Nack.Message;
            }
            else
            {
                return Constants.SUCCESS;
            }

        }
    }
}
